package threads;
//List数据结构实验
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class ListTest {
    public static void main(String [] args) throws InterruptedException {
        List<String> unsafeList = new ArrayList<>();//写
        //若用此数据格式，并发数据将不安全
        List<String> safeList = Collections.synchronizedList(new ArrayList<String>());//写
        //此数据结构是安全的，采用Collections.synchronizedList修饰
        CopyOnWriteArrayList<String> safeList2 = new CopyOnWriteArrayList<>();
        //基于复制的非阻塞，适合读
        ListThread lt = new ListThread(unsafeList);//往list有序列表中加入数据
        ListThread lt1 = new ListThread(safeList);
        ListThread lt2 = new ListThread(safeList2);
        for (int i = 0; i <10; i++) {
            Thread t = new Thread(lt, String.valueOf(i));
            t.start();//线程开始执行
            Thread t1 = new Thread(lt1, String.valueOf(i));
            t1.start();
            Thread t2 = new Thread(lt2, String.valueOf(i));
            t2.start();
        }
        Thread.sleep(2000);
        System.out.println("ArrayList<>()数据大小为：" + lt.list.size());
        System.out.println("Collections。synchronizedList()数据大小是：" + lt1.list.size());
        System.out.println("CopyOnWriteArrayList<>数据大小是：" + lt2.list.size());
//        for (int i = 0; i < lt.list.size(); i++)
//        {
//            System.out.println(lt.list);
//        }
        for (String s:lt1.list
             ) {
            System.out.print(s+"  ");

        }
        System.out.println();
        for (String s1:lt1.list)
        {
            System.out.print(s1+"  ");
        }
        System.out.println();
        for (String s2:lt2.list)
        {
            System.out.print(s2+"  ");
        }

    }
}
class ListThread implements Runnable
{
    public List<String> list;//返回有序列表的对象
    public ListThread(List<String> list)
    {
        this.list=list;
    }
    public void run()
    {
        int i=0;
        while(i<10)
        {
            try{
                Thread.sleep(10);//睡觉
            }catch(InterruptedException e)
            {
                e.printStackTrace();
            }
            list.add(Thread.currentThread().getName());//往ArrayList有序列表中加如元素
            i++;//加入十次
        }
    }
}